import re
from django.core.exceptions import ValidationError
from django.core.validators import RegexValidator

from django.shortcuts import render,HttpResponse,redirect

from django02.models import UserInfo, Department,BettyNumbers
from django.utils.safestring import mark_safe

from django02.util.Pagination import Pagination
from django02.util.BootStrapModelForm import BootStrapModelForm
# Create your views here.

def test(request):
    users = UserInfo.objects.all()
    departs = Department.objects.all()

    if request.method == 'POST':
        name = request.POST.get('user')
        password = request.POST.get('password')
        age = request.POST.get('age')
        gender = request.POST.get('gender')
        account = request.POST.get('account')
        depart_id = 2
        print(name,password,age,gender,account,depart_id)
        UserInfo.objects.create(name=name, password=password, age=age, gender=gender, account=account, depart_id=depart_id)
    # for user in users:
    #     print(user.name)
    return render(request, 'test2.html', {'users':users,'departs':departs})

def delete(request):
    nid = request.GET.get('nid')
    UserInfo.objects.get(id=nid).delete()
    return redirect('/d2/test/')

def index(request):
    return render(request, 'index.html')

def depart_list(request):
    departs = Department.objects.all()
    page_object = Pagination(request,departs)
    context = {
        'departs': page_object.page_queryset,
        'page_str':page_object.html(),
    }
    return render(request,'depart.html',context)

def depart_add(request):
    # 添加部门
    if request.method == 'GET':
        return render(request,'depart_add.html')

    title = request.POST.get('title')
    Department.objects.create(title=title)
    return redirect('/d2/depart/')

def depart_delete(request):
    nid = request.GET.get('nid')
    Department.objects.get(id=nid).delete()
    return redirect('/d2/depart/')

def depart_edit(request,nid):
    if request.method == 'GET':
        title = Department.objects.filter(id=nid).first()
        return render(request,'depart_edit.html',{'title':title})
    title = request.POST.get('title')
    Department.objects.filter(id=nid).update(title=title)
    return redirect('/d2/depart/')

def user_list(request):
    users = UserInfo.objects.all()
    page_object = Pagination(request,users)
    context ={
        'users':page_object.page_queryset,
        'page_str':page_object.html()
    }
    return render(request,'user_list.html', context)


# 使用modelform
from django import forms

class UserForm(forms.ModelForm):
    class Meta:
        model = UserInfo
        fields = ('name', 'password', 'age', 'gender', 'account', 'depart','create_time')
        # fields = '__all__'

    # 添加属性
    def __init__(self,*args,**kwargs):
        super(UserForm,self).__init__(*args,**kwargs)
        # super().__init__(*args,**kwargs)
        for name,field in self.fields.items():
            # 'autocomplate':'off' 去掉历史显示
            if name == 'create_time':
                field.widget.attrs = {'class': 'form-control', 'placeholder': field.label,'autocomplate':'off'}
            else:
                field.widget.attrs={'class':'form-control','placeholder':field.label}

            # # 如上需要保留原来的属性
            # if field.widget.attrs:
            #     field.widget.attrs['class'] = 'form-control'
            #     field.widget.attrs['placeholder'] = field.label
            # else:
            #     field.widget.attrs = {'class': 'form-control', 'placeholder': field.label}

def user_add(request):
    if request.method == 'GET':
        form = UserForm()
        return render(request,'user_add.html',{'form':form})
    form = UserForm(request.POST)
    if form.is_valid():
        form.save()
        return redirect('/d2/users/')
    return render(request,'user_add.html',{'form':form})

def user_edit(request,nid):
    user = UserInfo.objects.filter(id=nid).first()
    if request.method == 'GET':
        # instance
        form = UserForm(instance=user)
        return render(request,'user_edit.html',{'form':form})
    # instance=user 变成修改，如果没有则变成新增
    form = UserForm(request.POST,instance=user)
    if form.is_valid():
        form.save()
        return redirect('/d2/users/')
    return render(request,'user_edit.html',{'form':form})

def user_delete(request,nid):
    UserInfo.objects.filter(id=nid).delete()
    return redirect('/d2/users/')


# 靓号管理
# class BettryModelForm(forms.ModelForm):
#     # 验证方式1：
#     # mobile = forms.CharField(max_length=11,
#     #                          validators=[RegexValidator(regex=r'^1[3-9]\d{9}$',message='手机格式错误'),],
#     #                          )
#     class Meta:
#         model = BettyNumbers
#         fields = '__all__'
#         # fields = ['id'] 选择字段
#         # fields = '__all__' 全部字段
#         # exclude = ['id']  不包含字段
#
#     def __init__(self,*args,**kwargs):
#         super(BettryModelForm,self).__init__(*args,**kwargs)
#         for name,field in self.fields.items():
#             field.widget.attrs={'class':'form-control','placeholder':field.label}
#
#     # 验证方式2 钩子方法
#     def clean_mobile(self):
#         mobile = self.cleaned_data.get('mobile')
#         if len(mobile) != 11:
#             raise ValidationError('手机位数不对')
#         if not re.match(r'^1[3-9]\d{9}$',mobile):
#             raise ValidationError('手机号格式不正确')
#         return mobile

class BettryModelForm(BootStrapModelForm):
    # 验证方式1：
    # mobile = forms.CharField(max_length=11,
    #                          validators=[RegexValidator(regex=r'^1[3-9]\d{9}$',message='手机格式错误'),],
    #                          )
    class Meta:
        model = BettyNumbers
        fields = '__all__'
        # fields = ['id'] 选择字段
        # fields = '__all__' 全部字段
        # exclude = ['id']  不包含字段

    # 验证方式2 钩子方法
    def clean_mobile(self):
        mobile = self.cleaned_data.get('mobile')
        if len(mobile) != 11:
            raise ValidationError('手机位数不对')
        if not re.match(r'^1[3-9]\d{9}$',mobile):
            raise ValidationError('手机号格式不正确')
        return mobile

def bettry_list(request):
    # for i in range(200):
    #     BettyNumbers.objects.create(mobile='13278564932',price=12,level=2,status=2)
    # data_dict = {}
    # value = request.GET.get('query','')

    # # 分页
    # page = int(request.GET.get('page',1))
    # page_size = 10
    # start_size = (page - 1) * page_size
    # end_size = page * page_size
    #
    # if value:
    #     data_dict["mobile__contains"] = value
    # bettrys = BettyNumbers.objects.filter(**data_dict)
    #
    # total_count = BettyNumbers.objects.filter(**data_dict).count()  # 计算总条数
    # page_list = []
    # page_count,div = divmod(total_count, page_size)
    #
    # if div != 0:
    #     page_count += 1
    # # 根据当前页计算出显示页码
    # plus = 5 # 前五页后五页
    # # 极值处理
    # if page_count <= 2 * plus +1:
    #     page_start = 1
    #     page_end = page_count
    # else:
    #     # 当前页小于 plus 时
    #     if page <= plus:
    #         page_start = 1
    #         page_end = 2 * plus + 1
    #     else:
    #         # 当前页超过总页码
    #         if (page + plus) > page_count:
    #             page_start = page_count - 2 * plus
    #             page_end = page_count
    #         else:
    #             page_start = page - plus
    #             page_end = page + plus
    #
    # # 首页
    # if page == 1:
    #     page_list.append('<li class="disabled"><a href="?page={}">首页</a></li>'.format(1))
    # else:
    #     page_list.append('<li><a href="?page={}">首页</a></li>'.format(1))
    #
    # # 上一页
    # if page == 1:
    #     page_list.append('<li class="disabled"><a href="?page={}">上一页</a></li>'.format(1))
    # else:
    #     page_list.append('<li><a href="?page={}">上一页</a></li>'.format(page - 1))
    #
    # for i in range(page_start,page_end + 1):
    #     if i == page:
    #         page_list.append('<li class="active"><a href="?page={}">{}</a></li>'.format(i, i))
    #     else:
    #         page_list.append('<li><a href="?page={}">{}</a></li>'.format(i,i))
    # # 下一页
    # if page == page_count:
    #     page_list.append('<li class="disabled"><a href="?page={}">下一页</a></li>'.format(page_count))
    # else:
    #     page_list.append('<li><a href="?page={}">下一页</a></li>'.format(page + 1))
    #
    # # 尾页
    # if page == page_count:
    #     page_list.append('<li class="disabled"><a href="?page={}">尾页</a></li>'.format(page_count))
    # else:
    #     page_list.append('<li><a href="?page={}">尾页</a></li>'.format(page_count))
    #
    # # 跳转
    # search_str =  """
    # <li>
    #     <form method="get" style="float: left;">
    #         <input style="position: relative;float: left;display: inline-block;width: 88px" type="text" class="form-control" name="page" placeholder="页码">
    #         <button class="btn btn-default" type="submit">跳转</button>
    #     </form>
    # </li>
    # """
    # page_list.append(search_str)
    #
    # page_str = mark_safe(''.join(page_list))

    '''
    <li><a href="?page=1">1</a></li>
    '''
    # 使用自定义组件
    data_dict = {}
    value = request.GET.get('query', '')  # 条件检索
    if value:
        data_dict["mobile__contains"] = value
    bettrys = BettyNumbers.objects.filter(**data_dict)
    # bettrys = BettyNumbers.objects.all()
    page_object = Pagination(request,bettrys)
    context ={
        'bettrys':page_object.page_queryset,
        'page_str':page_object.html(),
        'value':value,
    }
    # 排序
    # bettrys = BettyNumbers.objects.all().order_by('id') # order_by('id') 正序，order_by('-id') 倒序
    return render(request,'betty_list.html',context)

def bettry_add(request):
    if request.method == 'GET':
        form = BettryModelForm()
        return render(request,'bettry_add.html',{'form':form})
    form = BettryModelForm(request.POST)
    if form.is_valid():
        form.save()
        return redirect('/d2/bettry/')
    return render(request,'bettry_add.html',{'form':form})

def bettry_delete(request,nid):
    BettyNumbers.objects.filter(id=nid).delete()
    return redirect('/d2/bettry/')

# 修改
class BettryWditModelForm(forms.ModelForm):
    # 验证方式1：mobile加上display=True时，手机号不能编辑
    mobile = forms.CharField(max_length=11,
                             validators=[RegexValidator(regex=r'^1[3-9]\d{9}$',message='手机格式错误'),],
                             )
    class Meta:
        model = BettyNumbers
        fields = '__all__'
        # fields = ['id'] 选择字段
        # fields = '__all__' 全部字段
        # exclude = ['id']  不包含字段

    def __init__(self,*args,**kwargs):
        super(BettryWditModelForm,self).__init__(*args,**kwargs)
        for name,field in self.fields.items():
            field.widget.attrs={'class':'form-control','placeholder':field.label}

    # 钩子函数，编辑时手机号不能改重复
    def clean_mobile(self):
        mobile = self.cleaned_data.get('mobile')
        # 除去自己以外的，exclude(id=1)表示id！=1的，exists存在，True/False
        exists = BettyNumbers.objects.filter(mobile=mobile).exclude(id=self.instance.pk).exists()
        if exists:
            raise ValidationError("手机号重复")
    #
    # def clean_mobile(self):
    #     mobile = self.cleaned_data.get('mobile')
    #     if len(mobile) != 11:
    #         raise ValidationError('手机位数不对')
    #     if not re.match(r'^1[3-9]\d{9}$',mobile):
    #         raise ValidationError('手机号格式不正确')
    #     return mobile
def bettry_edit(request,nid):
    bettry = BettyNumbers.objects.filter(id=nid).first()
    if request.method == 'GET':
        form = BettryModelForm(instance=bettry)
        return render(request,'bettry_edit.html',{'form':form})

    form = BettryModelForm(request.POST,instance=bettry)
    if form.is_valid():
        form.save()
        return redirect('/d2/bettry/')
    return render(request,'bettry_edit.html',{'form':form})
    


